package ViewListener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import Command.Command;
import Command.SqlStringChecker;
import Controller.MainController;
import Model.Connection;
import View.MainView;
import View.OpenDialog;
import View.SaveDialog;

public class MainViewActionListener implements ActionListener{

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String ac = e.getActionCommand();
		MainView mainView = (MainView) MainController.GetViewByName(MainController.MAIN_VIEW_NAME);
		switch(ac)
		{
		case "Open":
			OpenDialog openDlg = new OpenDialog(mainView);
			openDlg.show();
			break;
		case "Save as":
			SaveDialog saveDlg = new SaveDialog(mainView);
			saveDlg.show();
			break;
		case "Exit":
			MainController.CloseView(MainController.MAIN_VIEW_NAME);
			break;	
		case "Clear":			
			mainView.clearAllSQL();
			break;
		case "Execute":			
			SqlStringChecker checker = new SqlStringChecker();			
			mainView.ClearAllItemInResult();
			String sqlSend = deleteComment(mainView);

			if(sqlSend.trim().equals(""))
			{
				// Warning message
				JPanel panel = null;							
				JOptionPane.showMessageDialog(panel, "Empty sql: Please type sql commands!", 
					    "Warning!", JOptionPane.WARNING_MESSAGE);				
			}
			else
			{
				ArrayList<Command> commandsSend = checker.splitCommand(sqlSend);	
				// Code send commands below
				Connection.clientThread.setCommands(commandsSend);
				synchronized (Connection.clientThread) {
					Connection.clientThread.notify();
				}				
			}
			
			break;
		}
	}

	private String deleteComment(MainView mainView)
	{
		String input = mainView.getSQL();
		String ret = "";
		
		for(int i = 0 ; i < input.length(); i++)
		{
			if (!mainView.isComment(i))
			{
				ret += input.charAt(i);
			}
		}
		
		return ret;
	}
}
